package com.hbnu.exercise.mysql;

import java.sql.*;
import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Scanner;

public class DatabaseDemo04
{
    public static void main(String[] args)
    {
        Map<String, String> loginInfo = LoginUI();

        boolean result = VerifyLoginInfo(loginInfo);
        if (result)
            System.out.println("登录成功");
        else
            System.out.println("登录失败");
    }

    private static boolean VerifyLoginInfo(Map<String, String> loginInfo)
    {
        boolean flag = false;

        String username = loginInfo.get("username");
        String password = loginInfo.get("password");

        try
        {
            Class.forName("com.mysql.cj.jdbc.Driver");

            String url = "jdbc:mysql://localhost:3306/class2210?serverTimezone=GMT&useSSL=false&characterEncoding=utf-8";
            String user = "root";
            String pwd = "123456";

            Connection connection = DriverManager.getConnection(url, user, pwd);

            String sql = "SELECT * FROM tb_user WHERE username = ? AND password = ?";

            PreparedStatement preparedStatement = connection.prepareStatement(sql);

            preparedStatement.setString(1, username);
            preparedStatement.setString(2, password);

            ResultSet resultSet = preparedStatement.executeQuery();

            if (resultSet.next())
                flag = true;

            resultSet.close();
            preparedStatement.close();
            connection.close();
        } catch (Exception e)
        {
            throw new RuntimeException(e);
        }

        return flag;
    }

    private static Map<String,String> LoginUI()
    {
        Map<String, String> loginInfo = new HashMap<>();

        Scanner scanner = new Scanner(System.in);

        System.out.println("请输入您的账号");
        String username = scanner.nextLine();
        System.out.println("请输入您的密码");
        String password = scanner.nextLine();

        loginInfo.put("username", username);
        loginInfo.put("password", password);

        return loginInfo;
    }
}
